package com.xaicode.auth.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.xaicode.auth.annotation.Log;
import com.xaicode.auth.domain.Result;
import com.xaicode.auth.domain.params.IdsParam;
import com.xaicode.auth.entity.SysMenu;
import com.xaicode.auth.enums.BusinessType;
import com.xaicode.auth.security.domain.params.SysMenuQueryParam;
import com.xaicode.auth.service.ISysMenuService;
import com.xaicode.auth.utils.GlobalValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 菜单管理接口
 * 
 * @date 2024/12/19
 */
@RestController
@RequestMapping("/api/system/menu")
public class SysMenuController {

    @Autowired
    private ISysMenuService sysMenuService;


    @Log(title = "查看菜单列表", businessType = BusinessType.QUERY, isSaveResponseData = false)
    @SaCheckPermission("system:menu:list")
    @PostMapping("/list")
    public Result<?> list(@RequestBody SysMenuQueryParam param) {
        List<SysMenu> menus = sysMenuService.list(param);
        return Result.ok(menus);
    }

    @Log(title = "新增菜单", businessType = BusinessType.INSERT)
    @SaCheckPermission("system:menu:add")
    @PostMapping("/create")
    public Result<?> create(@RequestBody SysMenu entity) {
        sysMenuService.save(entity);
        return Result.ok();
    }

    @Log(title = "修改菜单", businessType = BusinessType.UPDATE)
    @SaCheckPermission("system:menu:edit")
    @PostMapping("/update")
    public Result<?> update(@RequestBody SysMenu entity) {
        GlobalValidator.notNull(entity.getId(), "id不能为空");
        sysMenuService.updateById(entity);
        return Result.ok();
    }

    @Log(title = "删除菜单", businessType = BusinessType.DELETE)
    @SaCheckPermission("system:menu:del")
    @PostMapping("/delete")
    public Result<?> delete(@RequestBody IdsParam<Integer> ids) {
        List<Integer> idList = ids.getIds();
        // TODO 删除菜单需判定绑定关系
        sysMenuService.removeByIds(idList);
        return Result.ok();
    }


    /**
     * 获取全部菜单路由
     *
     * @return .
     */
    @PostMapping("/routers")
    public Result<?> routers() {
        String userId = StpUtil.getLoginIdAsString();
        List<SysMenu> menus = sysMenuService.getMenusByUserId(userId);
        return Result.ok(menus);
    }

}
